<?php

use Ifsnop\Mysqldump as IMysqldump;

function baidupan_dump()
{
	if (function_exists('set_time_limit')) {
		set_time_limit(0);
	}

	$suffix = wp_date('j');
	$temp_dir = sys_get_temp_dir() . '/';
	$filename = 'db_' . DB_NAME . '_' . $suffix;
	$temp = $temp_dir . $filename . '.sql';
	try {
		$dump = new IMysqldump\Mysqldump('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASSWORD);
		$dump->start($temp);
	} catch (\Exception $e) {
		if (file_exists($temp)) unlink($temp);
		return;
	}

	//打包文件
	$file = $temp_dir . $filename . '.zip';
	$zip = new \ZipArchive;
	if ($zip->open($file, ZIPARCHIVE::CREATE) === true) {
		$zip->addFile($temp, $filename . '.sql');
		$zip->close();
		if (file_exists($temp)) unlink($temp);
	} else {
		if (file_exists($temp)) unlink($temp);
		return;
	}

	$buffer = file_get_contents($file);
	if (file_exists($file)) unlink($file);
	echo base64_encode($buffer);
	exit;
}
add_action('wp_ajax_dump', 'baidupan_dump');
